/*
 * package.c
 *
 *  Created on: 2013-5-8
 *      Author: xkaying
 */

#include "package.h"
#include "../common/list.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>

struct _package
{
	char *name; //包名字
	//子包数量
	List *plist;
	List *importlist;
	//接口列表
	List *ilist;
	//类列表
	List *clist;
	//枚举列表
	List *elist;
	Package *super;
};

Package *PackageInit(char *name)
{
	Package *package;
	package = (Package*) malloc(sizeof(package));
	package->name = name;
	package->plist = 0;
	package->importlist=0;
	package->ilist = 0;
	package->clist = 0;
	package->elist = 0;
	package->super=0;
	return package;
}
//添加一个子包,如果该子包存在则返回子包
Package *PackageAppend(Package *package, char *name)
{
	assert(package);
	if (package->plist == 0) {
		package->plist = ListInit();
	}
	Package *subp;
	//枚举所有子包
	ListCursor *pcursor;
	pcursor = ListGetCursor(package->plist);
	subp = (Package*) ListForeach(package->plist, pcursor);
	while (subp) {
		if (subp->name == name) {
			return subp;
		}
		subp = (Package*) ListForeach(package->plist, pcursor);
	}
	subp = PackageInit(name);
	subp->super=package;
	//返回子包
	return subp;
}

Package *PackageAppendImport(Package *package,Import *import)
{
	assert(package);
	assert(import);
	if(package->importlist==0){
		package->importlist=ListInit();
	}else{
		//判断是否重复
		ListCursor *pcursor;
		Import *pt;
		pcursor=ListGetCursor(package->importlist);
		pt=(Import*)ListForeach(package->importlist,pcursor);
		while(pt){
			if(!ImportCompare(import,pt)){
				printf("警告:import导入相同的包,只有一条起作用.\n");
				printf("包名:");
				ImportPrint(import,stdout);
				printf("\n");
				ImportFree(import);
				return package;
			}
			pt=(Import*)ListForeach(package->importlist,pcursor);
		}
	}
	ListPush(package->importlist,import);
	return package;
}

//为包添加一个类
void PackageAppendClass(Package *package, Class *pclass)
{
	assert(package);
	assert(pclass);

	ListCursor *pcursor;

}
//添加一个枚举类型
void PackageAppendEnum(Package *package, Enum *penum)
{
	assert(package);
	assert(penum);
	if(package->elist==0){
		package->elist=ListInit();
	}
	ListPush(package->elist,penum);
}

void PackageAppendInterface(Package *package, Interface *pif)
{
	assert(package);
	assert(pif);
	if(package->ilist==0){
		package->ilist=ListInit();
	}
	ListPush(package->ilist,pif);
}
